<template>
    <div class="common-layout">
        <el-container>
            <el-header style="border: 2px solid #dddddd;height: 80px;margin-bottom: 10px;">
                <el-row style="margin-top: 20px;">
                    <el-input placeholder="请输入产品名称" v-model="c.productName" style="width:240px;"></el-input>
                    <el-input placeholder="请输入产品编号" v-model="c.productNo" style="width: 240px;"></el-input>
                    <el-input placeholder="请输类别名称" v-model="c.typeName" style="width: 240px;"></el-input>
                    <el-button type="primary" @click="getShow">查询</el-button>
                </el-row>
            </el-header>
            <el-container style="height: 810px;">
                <el-aside width="200px" style="border: 2px solid #dddddd;margin-right: 10px;">

                    <el-input v-model="filterText" class="w-60 mb-2" placeholder="关键词" />
                    <el-tree ref="treeRef" style="max-width: 600px" class="filter-tree" :data="data"
                        :props="defaultProps" default-expand-all :filter-node-method="filterNode"
                        @node-click="handleNodeClick" :expand-on-click-node="false" />

                </el-aside>
                <el-main style="border: 2px solid #dddddd;">
                    <el-button type="success" @click="open(null)">新增</el-button>
                    <el-table :data="tableData" border style="width: 100%;height: 650px;">
                        <el-table-column type="index" width="55" label="序号" />
                        <el-table-column prop="productName" label="产品名称" />
                        <el-table-column prop="productNo" label="产品编号" />
                        <el-table-column prop="typeName" label="所属类别" />
                        <el-table-column prop="unit" label="单位" />
                        <el-table-column prop="specification" label="规格型号" />
                        <el-table-column prop="price" label="单价" />
                        <el-table-column prop="productDescription" label="产品说明" />
                        <el-table-column prop="name" label="操作">
                            <template v-slot="scoped">
                                <el-button link type="primary" size="small" @click="open(scoped.row)">修改</el-button>
                                <el-button link type="danger" size="small" @click="getDelete(scoped.row)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <!-- 分页 -->
                    <el-pagination v-model:current-page="p.index" v-model:page-size="p.size"
                        :page-sizes="[15, 20, 25, 30]" :background="true"
                        layout="total, sizes, prev, pager, next, jumper" :total="p.count" />
                </el-main>
                <!-- 新增对话框 -->
                <el-dialog v-model="logic.isOpen" :title="logic.title" width="500">
                    <el-form label-width="120">
                        <el-form-item label="产品名称">
                            <el-input v-model="add.productName" />
                        </el-form-item>
                        <el-form-item label="产品编号">
                            <el-input v-model="add.productNo" />
                        </el-form-item>
                        <el-form-item label="所属类型">
                            <el-cascader :options="options" :props="props1" clearable @change="handleChange"
                                :show-all-levels="false" v-model="add.typeId" />
                        </el-form-item>
                        <el-form-item label="单位">
                            <el-input v-model="add.unit" />
                        </el-form-item>
                        <el-form-item label="规格型号">
                            <el-input v-model="add.specification" />
                        </el-form-item>
                        <el-form-item label="单价">
                            <el-input v-model="add.price" />
                        </el-form-item>
                        <el-form-item label="产品说明">
                            <el-input v-model="add.productDescription" textarea />
                        </el-form-item>
                        <el-form-item label="产品照片">
                            <el-input v-model="add.img" />
                            <el-upload class="avatar-uploader" action="http://localhost:7183/api/UpFile/File"
                                :show-file-list="false" :on-success="handleAvatarSuccess"
                                :before-upload="beforeAvatarUpload">
                                <img v-if="add.img" :src="add.img" class="avatar" />
                                <el-icon v-else class="avatar-uploader-icon">
                                    <Plus />
                                </el-icon>
                            </el-upload>
                        </el-form-item>
                    </el-form>
                    <template #footer>
                        <div class="dialog-footer">
                            <el-button @click="logic.isOpen = false">取消</el-button>
                            <el-button type="primary" @click="save()">保存</el-button>
                        </div>
                    </template>
                </el-dialog>
            </el-container>
        </el-container>
    </div>
</template>
<script lang="ts" setup>
import axios from 'axios';
import { onMounted, reactive, ref, watch } from 'vue';
import { read } from '../../stores/host'
import {type TreeInstance } from 'element-plus'
//生命周期钩子
onMounted(()=>{
    getShow()
    GetTree()
})
//表格数据
const tableData =ref([])
//分页
const p=reactive({
    index:1,
    size:15,
    count:0,
    page:0
})
//查询条件
const c= reactive({
    productName:"",
    productNo:"",
    typeName:""
})
//查询
const getShow=()=>{
    read.get("/inventoryread/api/Inventory/ShowProduct",{params:{index:p.index,size:p.size,productName:c.productName,productNo:c.productNo,typeName:c.typeName}}).then(res=>{
        tableData.value = res.data.data
        p.count=res.data.count
        p.page=res.data.page
    })
}
//监视分页
watch(p,()=>{
    getShow();
})
//逻辑对象
const logic=reactive({
    isOpen:false,
    title:"",
    isAdd:false
})
//打开对话框
const open=(row:any)=>{
    getCasc()
    logic.isOpen=true
    if(row==null){
        logic.title="新增产品档案"
        logic.isAdd=true
        add.productName=""
        add.productNo=generateCurrentDateBatch()
        add.typeId=null
        add.unit=""
        add.specification=""
        add.price=""
        add.productDescription=""
        add.img=""
        add.createPeople=""
    }else{
        logic.title="修改产品档案"
        logic.isAdd=false
        add.id=row.id
        add.productName=row.productName
        add.productNo=row.productNo
        add.typeId=row.typeId
        add.unit=row.unit
        add.specification=row.specification
        add.price=row.price
        add.productDescription=row.productDescription
        add.img=row.img
    }
    
}
//生成生产编号
function generateCurrentDateBatch() {
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    const hour = String(now.getHours()).padStart(2, '0');
    const minute = String(now.getMinutes()).padStart(2, '0');
    const second = String(now.getSeconds()).padStart(2, '0');
    return `${year}${month}${day}${hour}${minute}${second}`;
}
//新增对象
const add=reactive({
    id:"",
    productName:"",
    productNo:generateCurrentDateBatch(),
    typeId:null,
    unit:"",
    specification:"",
    price:"",
    productDescription:"",
    img:"",
    createPeople:"",
    updatePeople:""
})
//保存对话框
const save=()=>{
    if(logic.isAdd){
        read.post("/inventorywrite/api/Inventory/AddProduct", add).then(res => {
            if (res.data.code == 200) {
                ElMessage.success(res.data.message)
                getShow()
            } else {
                ElMessage.error(res.data.message)
            }
        })
    }
    else {
        read.post("/inventorywrite/api/Inventory/UpdateProduct", add).then(res => {
            if (res.data.code == 200) {
                ElMessage.success(res.data.message)
                getShow()
            } else {
                ElMessage.error(res.data.message)
            }
        })
    }

    logic.isOpen = false
}
//删除
const getDelete=(row:any)=>{
    ElMessageBox.confirm(
    '确认要删除吗?',
    '警告',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      read.post("/inventorywrite/api/Inventory/DeleteProduct", { id: row.id }).then(res => {
        if (res.data.code == 200) {
          ElMessage.success(res.data.message)
          getShow()
        } else {
          ElMessage.error(res.data.message)
        }
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '删除被取消',
      })
    })
}

//树型
const handleNodeClick = (data: any) => {
    debugger
    console.log(data)
    c.typeName=data.label
    getShow()
}
const filterText = ref('')
const treeRef = ref<TreeInstance>()

const defaultProps = {
    children: 'children',
    label: 'label',
}

watch(filterText, (val) => {
    treeRef.value!.filter(val)
})

const filterNode = (value: string, data: any) => {
    if (!value) return true
    return data.label.includes(value)
}
const data = ref([])
const GetTree = () => {
    read.get("/inventoryread/api/Inventory/TreeType").then(res => {
        data.value = res.data.data
    })
}






//级联选择器===================================================
const props1 = {
    checkStrictly: true,
    expandTrigger: 'hover' as const,
}
const options = ref([])
const getCasc = () => {
    read.get("/inventoryread/api/Inventory/TreeType").then(res => {
        options.value = res.data.data
    })
}
const handleChange = (value: any) => {
    console.log(value[value.length - 1]);

    add.typeId = value[value.length - 1]
}

//上传图片
import { Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox, type UploadProps } from 'element-plus'
const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
    //   imageUrl.value = URL.createObjectURL(uploadFile.raw!)
    add.img = response.data
}
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
    ElMessage.error('格式只能是JPG/PNG 格式的图片!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('大小不能超过2MB!')
    return false
  }
  return true
}
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>